package com.sdyeda.readiot.fx;

import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.sdyeda.readiot.ReadIotApplication;
import com.sdyeda.readiot.config.License;
import com.sdyeda.readiot.config.Setting;

import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.Alert.AlertType;
import javafx.stage.Stage;

public class Tray {

	public Tray() {
		
		Init();
	}

	public void Init() {
		if(!SystemTray.isSupported()) {
			return;
		}
		
		TrayIcon trayicon = new TrayIcon(Toolkit.getDefaultToolkit()
				.getImage(ReadIotApplication.class.getResource("/icon.png"))
				.getScaledInstance(16, 16, 0), "尾矿库自动数据采集系统");
		
		PopupMenu menu = new PopupMenu();
		MenuItem open = new MenuItem("打开主界面");
		MenuItem exit = new MenuItem("退出");
		MenuItem about = new MenuItem("注册信息...");
		//Menu set = new ("设置");
		
		

		menu.add(about);
		menu.add(new MenuItem("-"));
		menu.add(open);
		menu.add(new MenuItem("-"));
		menu.add(exit);
		
		trayicon.setPopupMenu(menu);
		
		about.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				Platform.runLater(()->{
					AlertType type = AlertType.INFORMATION;
					if((boolean)Setting.Get(Setting.ISREGISTERED) ==false) {
						type = AlertType.ERROR;
					}
					new Alert(type,License.getLicenseInfo()).show();
				});
			}
		});
		
		open.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				Platform.runLater(()->{
					Stage stage = ReadIotApplication.primaryStage;
					//System.out.println(stage);
					if(stage!=null) {
						stage.show();
						stage.toFront();
					}
				});
			}
		});
		
		exit.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				Platform.runLater(() -> {
					TextInputDialog dialog = new TextInputDialog();
					dialog.setContentText("请输入密码");
					dialog.setHeaderText("您确认退出自动采集系统吗？");
					dialog.setTitle("尾矿库自动数据采集系统");
					dialog.showAndWait();
					System.out.print(dialog.getResult());
					if(!Setting.Get(Setting.SET_PASSWORD).equals(dialog.getResult())){
						new Alert(AlertType.ERROR,"密码错误").show();
					}
					else {
						Platform.exit();
						System.exit(0);
					}
				});
				//
			}
		});
		
		trayicon.addActionListener(listener ->{
			Platform.runLater(()->{
				Stage stage = ReadIotApplication.primaryStage;
				if(stage!=null) {
					stage.show();
					stage.toFront();
				}
			});
		});
		
		try {
			SystemTray.getSystemTray().add(trayicon);
		} catch (AWTException e) {
			//e.printStackTrace();
		}
	}
}
